﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.RBACs;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;
using RBAC.Write.Domain.DTOs;

namespace RBAC.Write.API.Applications.PermissionsFiles
{
    public class RolesListHander : IRequestHandler<RolesListCommand, ResultsDTO<RolesListDTO>>
    {
        private readonly IBateRepository<RolesListDTO> role;
        private readonly IBateRepository<Permissions> permiss;

        public RolesListHander(IBateRepository<RolesListDTO> role, IBateRepository<Permissions> permiss)
        {
            this.role = role;
            this.permiss = permiss;
        }

        public async Task<ResultsDTO<RolesListDTO>> Handle(RolesListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                string sql = "SELECT * from roles a JOIN rolespermissions b ON a.RolesId=b.RolesId JOIN permissions c ON b.PermissionsId=c.PermissionsId GROUP BY a.RolesId";
                ResultsDTO<RolesListDTO> res = new ResultsDTO<RolesListDTO>();
                RolesListDTO rolesListDTO = new RolesListDTO();
                DapperHelper dapper = new DapperHelper();
                Permissions per = new Permissions();
                var list = role.GetAll(sql, rolesListDTO, dapper.RBACWrite).ToList();
                foreach (var item in list)
                {
                    string sqlThis = "SELECT c.PermissionsName from roles a JOIN rolespermissions b ON a.RolesId=b.RolesId JOIN permissions c ON b.PermissionsId=c.PermissionsId WHERE a.RolesId="+item.RolesId;
                    var perName= permiss.GetAll(sqlThis, per, dapper.RBACWrite).ToList();
                    item.State = item.State == "0" ? "启用" : "禁用";
                    item.Per=string.Join(",", perName.Select(x=>x.PermissionsName));
                    //item.Per = string.Join();
                }
                res.Data = list;
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
